# encoding=utf-8
import os
import sys
import time

import win32serviceutil
import win32service
import win32event
import servicemanager

import winerror

from py.uitls import WinUtil
from py.uitls.Logger import myLogger
from py.uitls.SManager import ServiceManager
import win32timezone

service_name = "Pythonbb"


class PythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = service_name  # 服务名
    _svc_display_name_ = "Python Service Tes22t"  # 服务在windows系统中显示的名称
    _svc_description_ = "This is a python service te22st code "  # 服务的描述

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.run = True

    def SvcDoRun(self):
        myLogger.info("service is run....")
        while self.run:
            myLogger.info("I am runing....")
            time.sleep(2)

    def SvcStop(self):
        myLogger.info("service is stop....")
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.run = False


def start_cmd():
    try:
        win32serviceutil.HandleCommandLine(PythonService);
    except Exception as e:
        myLogger.info(e)


if __name__ == '__main__':
    myLogger.info(sys.executable)
    myLogger.info(__file__)
    myLogger.info("启动参数：%s" % sys.argv)

    WinUtil.get_admin()
    if len(sys.argv) == 1:
        sm = ServiceManager(service_name);
        if not sm.is_exists():
            myLogger.info("服务不存在：%s" % service_name)
            sys.argv = [sys.argv[0], '--startup', 'auto', 'install']
            myLogger.info(sys.argv)
            win32serviceutil.HandleCommandLine(PythonService)  # 参数和上述定义类名一致
            myLogger.info("服务安装成功（初始化）！")

            sm.start()

        try:
            evtsrc_dll = os.path.abspath(servicemanager.__file__)
            servicemanager.PrepareToHostSingle(PythonService)
            servicemanager.Initialize('PythonService', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()
        except win32service.error as details:
            if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()

    else:
        # threading.Thread(run=start_cmd).start();
        win32serviceutil.HandleCommandLine(PythonService);
        myLogger.info("命令执行完成")

# pip install pywin32

# 安装服务
# python PythonService.py install
# 让服务自动启动
# python PythonService.py --startup auto install
# 启动服务
# python PythonService.py start
# 重启服务
# python PythonService.py restart
# 停止服务
# python PythonService.py stop
# 删除/卸载服务
# python PythonService.py remove
